package com.konne.nightmare.FastPublicOpinion.http;


import com.konne.nightmare.FastPublicOpinion.bean.CurrencyBean;
import com.konne.nightmare.FastPublicOpinion.bean.EditEventBean;
import com.konne.nightmare.FastPublicOpinion.bean.EventBean;
import com.konne.nightmare.FastPublicOpinion.bean.HomeBean;
import com.konne.nightmare.FastPublicOpinion.bean.LoginBean;
import com.konne.nightmare.FastPublicOpinion.bean.NearbyActivityBean;
import com.konne.nightmare.FastPublicOpinion.bean.OpinionDataBean;
import com.konne.nightmare.FastPublicOpinion.bean.OpinionDetailDataBean;
import com.konne.nightmare.FastPublicOpinion.bean.OrganizationIdPermissionBean;
import com.konne.nightmare.FastPublicOpinion.bean.SelectNearbyBean;
import com.konne.nightmare.FastPublicOpinion.bean.UserInfoBean;

import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitFactory {

    private final ApiService mApiService;

    private volatile static RetrofitFactory mRetrofitFactory;

    private volatile static RetrofitFactory mRetrofitLoginFactory;

    private volatile static RetrofitFactory mRetrofitSpecialFactory;

    private final OkHttpClient mOkHttpClient;

    public static JSONObject getJsonParams() {
        return new JSONObject();
    }

    private RetrofitFactory(String baseUrl, int type) {

        //创建日志拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//设定日志级别

        //拦截token
        if (type == 0) {
            //创建OkHttpClient
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .readTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .writeTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .addInterceptor(new AddTokenHead())//添加拦截器
                    .addInterceptor(httpLoggingInterceptor)//添加拦截器
                    .addInterceptor(new ReceivedCookiesInterceptor())
                    .addInterceptor(new AddCookiesInterceptor())
                    .build();
        } else {
            //创建OkHttpClient
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .readTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .writeTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                    .addInterceptor(new AddHead())//添加拦截器
                    .addInterceptor(httpLoggingInterceptor)//添加拦截器
                    .addInterceptor(new ReceivedCookiesInterceptor())
                    .addInterceptor(new AddCookiesInterceptor())
                    .build();
        }


        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava2转换器
                .client(mOkHttpClient)
                .build();

        //创建接口实现类
        mApiService = retrofit.create(ApiService.class);
    }


    /**
     * 此构造函数方法不可使用单例模式
     */
    private RetrofitFactory(String baseUrl, String key, String value) {

        //创建日志拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//设定日志级别


        //创建OkHttpClient
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                .readTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                .writeTimeout(ApiService.HTTP_TIME, TimeUnit.SECONDS)
                .addInterceptor(new AddHeadInterceptor(key, value))//添加拦截器
                .addInterceptor(httpLoggingInterceptor)//添加拦截器
                .addInterceptor(new ReceivedCookiesInterceptor())
                .addInterceptor(new AddCookiesInterceptor())
                .build();

        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava2转换器
                .client(mOkHttpClient)
                .build();

        //创建接口实现类
        mApiService = retrofit.create(ApiService.class);
    }


    /**
     * 该方式传递TOKEN
     */
    public static RetrofitFactory getInstance() {
        if (mRetrofitFactory == null) {
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null)
                    mRetrofitFactory = new RetrofitFactory(ApiService.BASE_URL, 1);
            }
        }
        return mRetrofitFactory;
    }

    /**
     * 该方式不传递TOKEN
     */
    public static RetrofitFactory getLoginInstance() {
        if (mRetrofitLoginFactory == null) {
            synchronized (RetrofitFactory.class) {
                if (mRetrofitLoginFactory == null)
                    mRetrofitLoginFactory = new RetrofitFactory(ApiService.BASE_URL, 0);
            }
        }
        return mRetrofitLoginFactory;
    }

    public static RetrofitFactory getSpecialInstance(String key, String value) {
        return new RetrofitFactory(ApiService.BASE_URL, key, value);
    }


    public ApiService API() {
        return mApiService;
    }

    public ObservableTransformer threadTransformer() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable observable) {
                return observable
                        .subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 获取部分权限（是否上报）
     */
    public void getOrganPermission(int organizationId, BaseObserver<OrganizationIdPermissionBean.ResponseDataBean> observer) {
        try {
            API().
                    getOrganPermission(organizationId)
                    .compose(threadTransformer())
                    .subscribe(observer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * app登录
     */

    public void login(JSONObject jsonObject, BaseObserver<LoginBean.DataBean> baseObserver) {
        try {
            API().
                    login(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过手机号获取激活验证码
     */

    public void getPhoneActivationMsg(JSONObject jsonObject, BaseObserver<CurrencyBean> baseObserver) {
        try {
            API().
                    getPhoneActivationMsg(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * app激活账号
     */

    public void activation(JSONObject jsonObject, BaseObserver<CurrencyBean> baseObserver) {
        try {
            API().
                    activation(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * app扫码登录
     */

    public void appAllow(JSONObject jsonObject, BaseObserver<CurrencyBean> baseObserver) {
        try {
            API().
                    appAllow(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 事件分析列表
     */

    public void selectEventPlanList(JSONObject jsonObject, BaseObserver<List<EventBean.RowsBean>> baseObserver) {
        try {
            API().
                    selectEventPlanList(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 手动修改事件状态功能
     */

    public void updateEventPlan(JSONObject jsonObject, BaseObserver<String> baseObserver) {
        try {
            API().
                    updateEventPlan(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询事件信息
     */

    public void selectEventPlanInfo(int eventId, BaseObserver<EditEventBean.DataBean> baseObserver) {
        try {
            API().
                    selectEventPlanInfo(eventId)
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 新增事件
     */

    public void save(JSONObject jsonObject, BaseObserver<String> baseObserver) {
        try {
            API().
                    save(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑事件
     */

    public void update(JSONObject jsonObject, BaseObserver<String> baseObserver) {
        try {
            API().
                    update(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除事件
     */

    public void delete(JSONObject jsonObject, BaseObserver<String> baseObserver) {
        try {
            API().
                    delete(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 综合分析
     */

    public void selectComprehensiveAnalysis(JSONObject jsonObject, BaseObserver<List<SelectNearbyBean.DataBean>> baseObserver) {
        try {
            API().
                    selectComprehensiveAnalysis(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 事件首发媒体查询数据
     */

    public void selectTheStarting(int eventId, BaseObserver<List<NearbyActivityBean.RowsBean>> baseObserver) {
        try {
            API().
                    selectTheStarting(eventId)
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当前登录人信息
     */

    public void getInfo(BaseObserver<UserInfoBean.DataBean> baseObserver) {
        try {
            API().
                    getInfo()
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 手动修改事件状态功能
     */

    public void sysfeedback(JSONObject jsonObject, BaseObserver<String> baseObserver) {
        try {
            API().
                    sysfeedback(RequestBody.create(null, jsonObject.toString()))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 首页预警分页查询
     */
    public void myWarning(int pageNum, int pageSize, BaseObserver<List<HomeBean.RowsBean>> baseObserver) {
        try {
            API().
                    myWarning(pageNum, pageSize)
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 舆情列表接口
     */
    public void postOpinionList(int pageNum, int pageSize, String requestBody, BaseObserver<List<OpinionDataBean.ResponseDataBean>> baseObserver) {
        try {
            API().
                    postOpinionList(pageNum, pageSize, RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 舆情详情
     */
    public void getOpinionDetail(int id, BaseObserver<OpinionDetailDataBean.ResponseDataBean> baseObserver) {
        try {
            API().
                    getOpinionDetail()
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加入收藏
     */
    public void postOpinionAddCollect(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionAddCollect(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消收藏
     */
    public void postOpinionCancelCollect(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionCancelCollect(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加入预警
     */
    public void postOpinionAddWarning(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionAddWarning(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消预警
     */
    public void postOpinionCancelWarning(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionCancelWarning(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加入简报
     */
    public void postOpinionAddBriefing(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionAddBriefing(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消简报
     */
    public void postOpinionCancelBriefing(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionCancelBriefing(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除舆情
     */
    public void postOpinionDelete(String requestBody, BaseObserver<String> baseObserver){
        try {
            API().
                    postOpinionDelete(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 舆情看板
     */
    public void postOpinionDataStatistics(String requestBody, BaseObserver<OpinionDataBean.ResponseStatisticalDataBean> baseObserver){
        try {
            API().
                    postOpinionDataStatistics(RequestBody.create(null, requestBody))
                    .compose(threadTransformer())
                    .subscribe(baseObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}